﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Universum.Infrastructure.Persistence;
using System.Security.Principal;
using System.Linq.Expressions;
using Universum.Infrastructure.Utils;
using Microsoft.Web.Mvc.Internal;
using Universum.Model.Domain;

namespace Universum.Controllers
{
	public class UniversumController :Controller
	{
		//private readonly IRepository _Repository;
		///// <summary>
		///// Gets the repository
		///// </summary>
		//[Obsolete("This method is obsollete and will be removed")]
		//public IRepository Repository
		//{
		//    get { return _Repository; }
		//}

		private readonly IPrincipal _CurrentUser;
		/// <summary>
		/// Gets the Principal
		/// </summary>
		public IPrincipal CurrentUser
		{
			get { return _CurrentUser; }
		}

		public UniversumController(IPrincipal principal)
			
		{
			_CurrentUser = principal;

			CurrentUsername = principal.Identity.Name;
		}

		
		private string _username;
		/// <summary>
		/// Gets/Sets the logged in username
		/// </summary>
		public string CurrentUsername
		{
			get
			{
				return _username;
			}
			set
			{
				_username = value;
			}
		}
		/// <summary>
		/// Gets the username in the request
		/// </summary>
		public string UsernameInRequest
		{
			get
			{
				if(this.RouteData.Values.ContainsKey("username"))
				return this.RouteData.Values["username"].ToString();
				return "";
			}
		}

		public RedirectToRouteResult RedirectToAction<TType>(Expression<Action<TType>> member) where TType:UniversumController
		{
			
			//string redirectTo = MemberUtil<TType>.MemberName<ActionResult>(member);
			var values = ExpressionHelper.GetRouteValuesFromExpression(member);
			return RedirectToAction( values["Action"].ToString(), values );
		}

		public ActionResult View<TType>(Expression<Func<TType, ActionResult>> member) where TType : UniversumController 
		{
			string viewname = MemberUtil<TType>.MemberName<ActionResult>(member);
			return View(viewname);
		}

		public ModelStateDictionary ValidateArticle(Article article)
		{
			if (article.Title.IsNullOrEmpty())
			{
				ModelState.AddModelError(
					"Title",
					"Title property cannot be null or empty");
			}
			if (article.Text.IsNullOrEmpty())
			{
				ModelState.AddModelError(
					"Text",
					"Text property cannot be null or empty");
			}
			if (article.Slug.IsNullOrEmpty())
			{
				ModelState.AddModelError(
					"Slug",
					"Slug property cannot be null or empty");
			}
			return ModelState;
		}
	}
}
